package com.portal.sso.core.server;

import cn.hutool.core.util.StrUtil;
import com.portal.sso.core.config.RespoingModelEnum;
import com.portal.sso.core.config.SsoConfig;
import com.portal.sso.core.exception.WhitelistException;
import com.portal.sso.core.model.RequestModel;
import com.portal.sso.core.util.CookieTools;
import org.springframework.beans.factory.annotation.Autowired;

import javax.security.auth.login.CredentialException;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public abstract class AbstractTokenManage {
    @Autowired
    TgtServerHander tgtServerHander;
    @Autowired
    JwtServerHander jwtServerHander;

    /**
     * 生成tgt
     * @param userId
     * @return
     */
    public final String GenerateTgt(String userId){


        String tgt = UUID.randomUUID().toString().replaceAll("-","");
        tgtServerHander.create(tgt,userId);

        return tgt;
    }

    /**
     * 生成Token
     * @param tgt
     * @param appId
     * @return
     */
    public final String GenerateToken(String tgt,String appId) throws WhitelistException{
        if(StrUtil.isNotEmpty(tgt)){
           if( tgtServerHander.isExist(tgt)){
              String userId = tgtServerHander.getKey(tgt);
               Map map = new HashMap<String,Object>();
               map.put(SsoConfig.SSO_USER_ID,userId);
               //获取秘钥
               String secret = GetSecret(appId);
               String jwt = jwtServerHander.createToken(map,secret);
               return jwt;
           }
        }
        return  null;
    }

    public final String GenerateToken(RequestModel requestModel) throws WhitelistException {
      return  GenerateToken(requestModel.getTgt(),requestModel.getAppId());
    }

    /**
     * 删除缓存并且清除cookie
     * @param response
     * @param tgt
     */
    public final void ClearUserId(HttpServletResponse response,String tgt){
        tgtServerHander.remove(tgt);
        CookieTools.clearCookieByName(response,SsoConfig.SSO_COOKIE_TGT);

    }

    /**
     * 添加cookie
     * @param response
     * @param tgt
     */
    public final void SetCooket(HttpServletResponse response,String tgt){
        //添加tgt到cookie
        CookieTools.addCookie(response,null,SsoConfig.SSO_COOKIE_PATH,SsoConfig.SSO_COOKIE_TGT,tgt,CookieTools.CLEAR_BROWSER_IS_CLOSED,true,false);

    }

    /**
     * 获取appid对应的秘钥
     * @param appId
     * @return
     */
    public abstract String GetSecret(String appId) throws WhitelistException;

    /**
     * 检查server是否在白名单中
     * @param appId
     * @param server 申请jwt的server的ip或域名
     * @return
     */
    public abstract boolean CheckAppId(String appId,String server);

    /**
     * 获取客户端的uri风格
     * @param appId
     * @return
     */
    public abstract String GetUriStyle(String appId);

    public abstract RespoingModelEnum GetRepModel(String appId);
}
